package cn.remex.core.util.imgs;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by guoqi on 2016/10/28.
 */
public class ImageHelper {
    /**
     * 通过判断图片的宽度和高度来确定是否是图片
     * @param imageInputStream 照片流
     * @return boolean
     */
    public static boolean isImage(InputStream imageInputStream) {
        Image img;
        try {
            img = ImageIO.read(imageInputStream);
            return !(img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 将图片转换为base64编码后的字符串
     * @param in
     * @return
     * @throws Exception
     */
    public static String imgToBase64(InputStream in) throws Exception{
        byte[] data = new byte[in.available()];
        in.read(data);
        in.close();
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    /**
     * 对字节数组字符串进行Base64解码并生成图片
     * @param base64
     * @param path
     * @return
     * @throws Exception
     */
    public static boolean base64ToImg(String base64, String path) throws Exception{
        if (base64 == null) {
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes = decoder.decodeBuffer(base64);
        for (int i = 0; i < bytes.length; ++i) {
            if (bytes[i] < 0) {//调整异常数据
                bytes[i] += 256;
            }
        }
        //生成jpeg图片
        OutputStream out = new FileOutputStream(path);
        out.write(bytes);
        out.flush();
        out.close();
        return true;
    }

}
